<template>
    <div class="h-full pt-8px header">
        <n-tabs type="card" class="w-full h-full" v-model:value="activeTab">
            <template #prefix>
                <div class="pl-16px va--3">
                    <jb-icon
                        icon="ant-design:sound-outlined"
                        class="inline text-20px"
                    ></jb-icon>
                    <span class="ml-10px text-18px">个人消息中心</span>
                </div>
            </template>
            <n-tab-pane name="notice" tab="通知" class="h-full">
                <jb-crud-page
                    ref="noticePage"
                    search-url="/api/admin/msgCenter/sysNoticeDatas"
                    :search-conditions="noticePageConditions"
                >
                    <template #conditions-form>
                        <n-input
                            v-model:value="noticePageConditions.keywords"
                            class="input"
                            type="text"
                            placeholder="输入关键字搜索"
                        />
                        <jb-select
                            v-model:value="noticePageConditions.type"
                            url="/api/admin/dictionary/options?typeKey=sys_notice_type"
                            filterable
                            class="w-120px"
                            placeholder="=通知类型="
                        >
                        </jb-select>
                        <jb-select
                            v-model:value="noticePageConditions.priorityLevel"
                            url="/api/admin/dictionary/options?typeKey=sys_notice_priority_level"
                            filterable
                            class="w-120px"
                            placeholder="=优先级="
                        >
                        </jb-select>
                        <jb-select
                            v-model:value="noticePageConditions.receiverType"
                            url="/api/admin/dictionary/options?typeKey=sys_notice_receiver_type"
                            filterable
                            class="w-140px"
                            placeholder="=接收者类型="
                        >
                        </jb-select>
                        <jb-select
                            v-model:value="noticePageConditions.readed"
                            url="/api/admin/dictionary/options?typeKey=options_boolean"
                            filterable
                            class="w-140px"
                            placeholder="=阅读状态="
                        >
                        </jb-select>
                    </template>
                    <template #opt>
                        <jb-btn icon="mdi:read"  type="primary" ghost @click="getNoticeSelect">标记已读</jb-btn>
                    </template>
                    <template #default="{ state }">
                        <vxe-table
                            ref="noticeTableRef"
                            border
                            :column-config="{ resizable: true }"
                            height="auto"
                            show-header-overflow
                            show-overflow="tooltip"
                            :row-config="{ isHover: true }"
                            :checkbox-config="{ trigger: 'row' }"
                            :seq-config="{ startIndex: state.tableStartIndex }"
                            align="center"
                            :data="state.list"
                        >
                            <jb-column type="checkbox" width="60"></jb-column>
                            <jb-column type="seq" title="序号" width="60"></jb-column>
                            <jb-column field="readed" title="状态" width="100">
                                <template #default="{ row }">
                                    <n-tag :type="row.readed ? 'success' : 'warning'">{{
                                        row.readed ? '已读' : '未读'
                                    }}</n-tag>
                                </template>
                            </jb-column>
                            <jb-column
                                field="title"
                                title="标题"
                                min-width="400"
                            ></jb-column>
                            <jb-column field="ak" title="有附件" width="100">
                                <template #default>
                                    <div class="flex justify-center cursor-pointer">
                                        <jb-icon icon="mdi:file"></jb-icon>
                                    </div>
                                </template>
                            </jb-column>
                            <jb-column field="typeName" title="类型" width="100">
                                <template #default="{ row }">
                                    <n-tag type="info">
                                        {{ row.typeName }}
                                    </n-tag>
                                </template>
                            </jb-column>
                            <jb-column
                                field="priorityLevelName"
                                title="优先级"
                                sortable
                                width="100"
                            >
                                <template #default="{ row }">
                                    <n-tag
                                        :type="
                                            row.priorityLevel == 1
                                                ? 'default'
                                                : row.priorityLevel == 2
                                                ? 'info'
                                                : 'error'
                                        "
                                    >
                                        {{ row?.priorityLevelName }}
                                    </n-tag>
                                </template>
                            </jb-column>
                            <jb-column
                                field="readCount"
                                title="已读数"
                                sortable
                                width="100"
                            ></jb-column>
                            <jb-column
                                field="receiverTypeName"
                                title="接收类型"
                                sortable
                                width="100"
                            >
                                <template #default="{ row }">
                                    <n-tag type="info">
                                        {{ row.receiverTypeName }}
                                    </n-tag>
                                </template>
                            </jb-column>
                            <jb-column
                                field="createTime"
                                title="创建时间"
                                min-width="200"
                            ></jb-column>
                            <jb-column
                                field="updateTime"
                                title="更新时间"
                                min-width="200"
                            ></jb-column>
                            <jb-column title="操作" width="200" fixed="right">
                                <template #default="{ row }">
                                    <jb-btn
                                        ref="sysNoticeRef"
                                        icon="mdi:eye"
                                        quaternary
                                        circle
                                        :tip-text="`${row.title}`"
                                        :drawer-component="NoticeDrawer"
                                        :drawer-title="`${row.title}`"
                                        :drawer-positive-text="`${
                                            row.readed
                                                ? '此通知已被标记为【已读】'
                                                : '标记已读'
                                        }`"
                                        :drawer-component-props="{
                                            id: row.id,
                                            type: 'sysNotice'
                                        }"
                                        :drawer-args="{
                                            negativeText: '关闭',
                                            defaultWidth: '1400',
                                            resizable: true
                                        }"
                                        @drawer-yes-click="markReaded"
                                    >
                                    </jb-btn>
                                </template>
                            </jb-column>
                        </vxe-table>
                    </template>
                </jb-crud-page>
            </n-tab-pane>
            <n-tab-pane name="todo" tab="待办" class="h-full">
                <jb-crud-page
                    ref="todoPage"
                    search-url="/api/admin/msgCenter/todoDatas"
                    :search-conditions="todoPageConditions"
                    :edit-component="TodoEdit"
                    @after-render="handleTodoAfterRender"
                >
                    <template #conditions-form>
                        <n-input
                            v-model:value="todoPageConditions.keywords"
                            class="input"
                            type="text"
                            placeholder="输入关键字搜索"
                        />
                        <jb-select
                            v-model:value="todoPageConditions.state"
                            url="/api/admin/dictionary/options?typeKey=todo_state"
                            filterable
                            class="w-120px"
                            placeholder="=状态="
                        >
                        </jb-select>
                        <jb-select
                            v-model:value="todoPageConditions.type"
                            url="/api/admin/dictionary/options?typeKey=todo_type"
                            filterable
                            class="w-140px"
                            placeholder="=类型="
                        >
                        </jb-select>

                        <jb-select
                            v-model:value="todoPageConditions.dateTimeColumn"
                            url="/api/admin/dictionary/options?typeKey=todo_datetime_column"
                            filterable
                            class="w-120px"
                            placeholder="=时间类型="
                        >
                        </jb-select>
                        <jb-date-range
                            v-model:value="todoPageConditions.dateRange"
                            format-pattern="yyyy-MM-dd"
                        ></jb-date-range>
                    </template>
                    <template #opt>
                        <n-button-group>
                            <jb-btn type="success" ghost @click="getTodoSelect(3)"
                                >标记已完成</jb-btn
                            >
                            <jb-btn type="warning" ghost @click="getTodoSelect(4)"
                                >标记已取消</jb-btn
                            >
                            <jb-btn type="error" ghost @click="getTodoSelect"
                                >删除</jb-btn
                            >
                            <jb-btn
                                ghost
                                type="primary"
                                @click="todoPage?.showEditModal('添加待办事项')"
                                >新待办</jb-btn
                            >
                        </n-button-group>
                    </template>
                    <template #default="{ state }">
                        <vxe-table
                            ref="todoTableRef"
                            border
                            :column-config="{ resizable: true }"
                            height="auto"
                            show-header-overflow
                            show-overflow="tooltip"
                            :checkbox-config="{ trigger: 'row' }"
                            :row-config="{ isHover: true }"
                            :seq-config="{ startIndex: state.tableStartIndex }"
                            align="center"
                            :data="state.list"
                        >
                            <jb-column type="checkbox" width="60"></jb-column>
                            <jb-column type="seq" title="序号" width="60"></jb-column>
                            <jb-column
                                field="title"
                                title="标题"
                                min-width="400"
                            ></jb-column>
                            <jb-column field="stateName" title="状态" width="100">
                                <template #default="{ row }">
                                    <span>{{ row.stateName }}</span>
                                </template>
                            </jb-column>

                            <jb-column field="typeName" title="类型" width="140">
                                <template #default="{ row }">
                                    <jb-tag-group :tags="row.typeName"> </jb-tag-group>
                                </template>
                            </jb-column>
                            <jb-column
                                field="priorityLevelName"
                                title="优先级"
                                sortable
                                width="100"
                            >
                                <template #default="{ row }">
                                    <n-tag
                                        :type="
                                            row.priorityLevel == 1
                                                ? 'default'
                                                : row.priorityLevel == 2
                                                ? 'info'
                                                : 'error'
                                        "
                                    >
                                        {{ row?.priorityLevelName }}
                                    </n-tag>
                                </template>
                            </jb-column>
                            <jb-column
                                field="readCount"
                                title="关联内容"
                                min-width="200"
                            ></jb-column>
                            <jb-column
                                field="specifiedFinishTime"
                                title="规定完成时间"
                                sortable
                                min-width="200"
                            >
                            </jb-column>
                            <jb-column
                                field="receiverTypeName"
                                title="完成时间"
                                sortable
                                min-width="200"
                            >
                            </jb-column>
                            <jb-column
                                field="receiverTypeName"
                                title="取消时间"
                                sortable
                                min-width="200"
                            >
                            </jb-column>
                            <jb-column
                                field="receiverTypeName"
                                title="创建者"
                                width="120"
                            >
                            </jb-column>
                            <jb-column
                                field="createTime"
                                sortable
                                title="创建时间"
                                min-width="200"
                            ></jb-column>
                            <jb-column
                                field="updateTime"
                                sortable
                                title="更新时间"
                                min-width="200"
                            ></jb-column>
                            <jb-column title="操作" width="180" fixed="right">
                                <template #default="{ row }">
                                    <jb-btn
                                        icon="mdi:eye"
                                        quaternary
                                        secondary
                                        circle
                                        class="mx-8px"
                                        :tip-text="`${row.title}`"
                                        :drawer-component="NoticeDrawer"
                                        :drawer-title="`${row.title}`"
                                        drawer-positive-text=""
                                        :drawer-component-props="{
                                            id: row.id,
                                            type: 'todo'
                                        }"
                                        :drawer-args="{
                                            negativeText: '关闭',
                                            defaultWidth: '1400',
                                            resizable: true
                                        }"
                                    >
                                    </jb-btn>
                                    <jb-btn
                                        tip-text="编辑"
                                        icon="uil:edit-alt"
                                        quaternary
                                        secondary
                                        class="mx-8px"
                                        type="warning"
                                        circle
                                        strong
                                        @click="
                                            todoPage?.showEditModal('编辑待办事项', {
                                                id: row.id
                                            })
                                        "
                                    ></jb-btn>
                                    <jb-btn
                                        tip-text="删除"
                                        icon="ant-design:delete-filled"
                                        secondary
                                        type="error"
                                        quaternary
                                        circle
                                        strong
                                        class="mx-8px"
                                        confirm-text="确定删除这条数据？"
                                        :url="`/api/admin/todo/delete/${row.id}`"
                                        @success="todoPage?.loadData()"
                                    ></jb-btn>
                                </template>
                            </jb-column>
                        </vxe-table>
                    </template>
                </jb-crud-page>
            </n-tab-pane>
        </n-tabs>
    </div>
</template>
<script setup lang="ts">
import {computed, onActivated, onMounted, reactive, ref} from 'vue'
import JbCrudPage from '@/components/_builtin/jb-crud-page/index.vue'

import { JBoltApi } from '@/utils/request'

import { ResData } from '@/typings/request'
import { DynamicComponentEmitArgs } from '@/typings/jbolt.components'
import TodoEdit from './components/todo-edit/index.vue'
import NoticeDrawer from './components/notice-drawer/index.vue'
import type { VxeTableInstance } from 'vxe-table'
import {useRoute} from "vue-router";
import {useAuthStore, useThemeStore} from "@/store";
import {storeToRefs} from "pinia";

const noticePage = ref<InstanceType<typeof JbCrudPage> | null>(null)
const noticePageConditions = reactive({
    keywords: '',
    type: '',
    priorityLevel: '',
    receiverType: '',
    readed: ''
})
const noticeTableRef = ref<VxeTableInstance<any>>()
function getNoticeSelect() {
    const $table = noticeTableRef.value
    if ($table) {
        const selectRecords = $table.getCheckboxRecords()
        if (selectRecords.length == 0) {
            window.$error('请选择通知再执行操作')
            return
        }
        let ids = selectRecords.map((obj) => obj.id).join(',')
        JBoltApi.get(`/api/admin/msgCenter/sysNoticeMarkMultiAsRead?ids=${ids}`).then(
            () => {
                noticePage.value?.loadData()
            }
        )
    }
}
const todoPage = ref<InstanceType<typeof JbCrudPage> | null>(null)
const todoPageConditions = reactive({
    keywords: '',
    type: '',
    state: '',
    sortColumn: '',
    sortType: '',
    dateTimeColumn: '',
    dateRange: ''
})
const todoTableRef = ref<VxeTableInstance<any>>()
function getTodoSelect(state: number) {
    const $table = todoTableRef.value
    if ($table) {
        const selectRecords = $table.getCheckboxRecords()
        if(selectRecords.length<=0){
            window.$message?.warning('请先选择要操作的行')
            return
        }

        let title = !state ? '提示' : (state===3?'标记完成':'标记取消')
        let content = !state ? '确认删除所选消息？' : (state===3?'确认标记完成所选消息？':'确认标记取消所选消息？')
        window.$dialog.warning({
            title: title,
            content: content,
            positiveText: '确定',
            negativeText: '取消',
            onPositiveClick: () => {
                let ids = selectRecords.map((obj) => obj.id).join(',')
                if (state) {
                    JBoltApi.get(
                        `/api/admin/todo/batchUpdateState?ids=${ids}&state=${state}`
                    ).then(() => {
                        todoPage.value?.loadData()
                    })
                } else {
                    JBoltApi.get(`/api/admin/todo/deleteByIds?ids=${ids}`).then(() => {
                        todoPage.value?.loadData()
                    })
                }
            }
        })


    }
}

const sysNoticeRef = ref(null)
async function markReaded({ close, componentProps }: DynamicComponentEmitArgs) {
    const res = await JBoltApi.get<ResData>(
        `/api/admin/msgCenter/sysNoticeMarkMultiAsRead?ids=${componentProps?.id}`
    )
    if (res.error) return
    close()
    noticePage.value?.loadData()
}
const route = useRoute()
const activeTab = ref('notice')


function handleTodoAfterRender(){
    if(useAuthStore().newTodo){
        todoPage?.value.showEditModal('添加待办事项')
        useAuthStore().newTodo = false
    }

}


onActivated(()=>{
    if(useAuthStore().newTodo){
        activeTab.value='todo'
    }
})

const { darkMode } = storeToRefs(useThemeStore())

const headerBgColor = computed(()=>{
    return darkMode.value ? '1A1A1C' : '#FFF'
})

</script>
<style scoped>
.header {
    background-color: v-bind(headerBgColor);
}
</style>
